import 'package:flutter/material.dart';
import 'package:flutter/cupertino.dart';
import 'function.dart';
import 'model/group_model.dart';
import 'widget/gradient_button.dart';
import 'util/ui_data.dart';

class AddPage extends StatefulWidget {
  final List<GroupModel> groups;
  final Color mainColor;
  AddPage(this.groups, this.mainColor);
  @override
  _AddPageState createState() => new _AddPageState(groups);
}

class _AddPageState extends State<AddPage> {
  _AddPageState(this.groups) {
    selectedGroup = groups[0].name;
  }

  List<GroupModel> groups;
  String selectedGroup;
  final scaffoldState = GlobalKey<ScaffoldState>();
  String account = "";
  String password = "";
  bool hidePass = true;
  var deviceSize;
  final GlobalKey<FormState> _formKey = new GlobalKey<FormState>();

  @override
  void initState() {
    super.initState();
  }

  String validateAccount(String value) {
    if (value == "") return "请输入手机号/邮箱";
    return null;
  }

  String validatePassword(String value) {
    if (value == "") return "请输入密码";
    return null;
  }

  login() async {
    var exist = await findDeviceByAccount(account);
    if (exist) {
      toast("账号已存在");
      return false;
    }
    Map loginInfo = await doLogin(account: account, password: password);
    if (loginInfo == null) {
      toast("登录出错");
    } else {
      var groupid = 1;
      for (GroupModel group in groups) {
        if (group.name == selectedGroup) {
          groupid = group.id;
          break;
        }
      }
      int id = await addDevice(
          groupid,
          account,
          password,
          rand(),
          rand(),
          loginInfo['sessionid'],
          loginInfo['userid']);
      toast("添加成功");
      Navigator.pop(context, "$id");
    }
  }

  @override
  Widget build(BuildContext context) {
    deviceSize = MediaQuery
        .of(context)
        .size;
    return new Scaffold(
      key: scaffoldState,
      appBar: new CupertinoNavigationBar(
        border: new Border(bottom: BorderSide.none),
        actionsForegroundColor: Colors.white,
        backgroundColor: widget.mainColor,
        middle: new Text(
          "添加账号",
          style: new TextStyle(
            color: Colors.white,
            fontWeight: FontWeight.normal,
          ),
        ),
      ),
      body: new SafeArea(
        child: new SingleChildScrollView(
          child: new Column(
            children: <Widget>[
              new Container(
                height: 100.0,
                child: ClipPath(
                  clipper: new ArcClipper(),
                  child: Stack(
                    children: <Widget>[
                      new Container(
                        width: double.infinity,
                        child: Image.asset(
                          "images/wky_logo.png",
                          width: 40.0,
                        ),
                      ),
                    ],
                  ),
                ),
              ),
              new Card(
                color: Colors.white,
                margin: EdgeInsets.all(20.0),
                elevation: 2.0,
                child: Form(
                  key: _formKey,
                  child: Padding(
                    padding: const EdgeInsets.all(18.0),
                    child: new Column(
                      mainAxisAlignment: MainAxisAlignment.center,
                      children: <Widget>[
                        new TextFormField(
                          decoration: new InputDecoration(
                            hintText: '请输入手机号/邮箱',
                            labelText: "账号",
                          ),
                          onSaved: (value) {
                            account = value;
                          },
                          validator: validateAccount,
                        ),
                        new TextFormField(
                          obscureText: this.hidePass,
                          decoration: new InputDecoration(
                            hintText: '请输入玩客云密码',
                            labelText: '密码',
                            suffixIcon: new IconButton(
                              icon: new Icon(
                                this.hidePass ? Icons.visibility : Icons.visibility_off,
                                color: Colors.black38,
                                size: 22.0,
                              ),
                              onPressed: () {
                                this.hidePass = !this.hidePass;
                                setState(() {});
                              },
                            ),
                          ),
                          onSaved: (value) {
                            password = value;
                          },
                          validator: validatePassword,
                        ),
                        new DropdownButtonHideUnderline(
                          child: new SafeArea(
                            child: new InputDecorator(
                              decoration: const InputDecoration(
                                labelText: '分组',
                                hintText: '请选择分组',
                              ),
                              child: new DropdownButton<String>(
                                //style: TextStyle(color: Colors.black),
                                isDense: true,
                                value: selectedGroup,
                                onChanged: (value) {
                                  setState(() {
                                    selectedGroup = value;
                                  });
                                },
                                items: groups.map((GroupModel group) {
                                  return new DropdownMenuItem<String>(
                                    value: group.name,
                                    child: new Text(group.name),
                                  );
                                }).toList(),
                              ),
                            ),
                          ),
                        ),
                        new SizedBox(
                          height: 30.0,
                        ),
                        new GradientButton(
                          onPressed: () async {
                            final FormState form = _formKey.currentState;
                            if (!form.validate()) {} else {
                              form.save();
                              login();
                            }
                          },
                          text: "添加账号",
                          splashColor: widget.mainColor,
                        ),
                        new SizedBox(
                          height: 10.0,
                        ),
                      ],
                    ),
                  ),
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }
}